package com.example.autopia.view.Activities

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatDelegate
import com.example.autopia.R
import com.example.autopia.model.Item.User
import com.example.autopia.model.Repositories.TestRepository
import com.example.autopia.utilities.PreferenceManager
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.ktx.auth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.google.firebase.ktx.Firebase

class SplashActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)

        window.decorView.apply {
            systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN
        }

        val handler = Handler(Looper.getMainLooper())
        val openBoardActivity = Runnable{
            val intent = Intent(this, OnBoardActivity::class.java)
            startActivity(intent)
            finish()
        }
        val openLoginActivity = Runnable{
            val intent = Intent(this, LoginActivity::class.java)
            startActivity(intent)
            finish()
        }
        val openMainActivity = Runnable{
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finish()
        }

        val onboardPreference: PreferenceManager = PreferenceManager(this@SplashActivity)
        if(onboardPreference.getBoolean("onboard")){
            val currentUser: FirebaseUser? = FirebaseAuth.getInstance().currentUser
            if (currentUser == null || Firebase.auth.currentUser?.isEmailVerified == false) {
                handler.postDelayed(openLoginActivity, 600)
            } else {
                handler.postDelayed(openMainActivity, 600)
            }
        } else {

            handler.postDelayed(openBoardActivity, 600)
        }

        val themePreference: PreferenceManager = PreferenceManager(this@SplashActivity)
        when (themePreference.getString("theme")) {
            null, "system" -> {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
            }
            "dark" -> {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
            }
            else -> {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
            }
        }
    }
}